#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : rascaler
# @Time :  2022/2/8 14:06
import base64
import hashlib
import hmac
import sys
# import urllib2
import urllib
import json
import time

# 自定义机器人的封装类
from datetime import datetime

import requests

# webhook = "https://oapi.dingtalk.com/robot/send?access_token=9ca2310ce1460d979c07076085ec98d28d905bbedf85c75ca0f48d0ca4176bdc"
from dateutil import rrule

from app.common.dateutils import DateUtils
from app.core.config import settings


class DingtalkRobot(object):
    MAX = 18
    INTERVAL = 70
    """docstring for DtRobot"""
    def __init__(self, token, secret):
        super(DingtalkRobot, self).__init__()
        self.token = token
        self.secret = secret
        self.lastSendTime = None
        self.sendCount = 0
        self.webhook = "https://oapi.dingtalk.com/robot/send"

    # text类型
    def sendText(self, msg, isAtAll=False, atMobiles=[]):
        data = {"msgtype": "text", "text": {"content": msg}, "at": {"atMobiles": atMobiles, "isAtAll": isAtAll}}
        return self.post(data)

    # markdown类型
    def sendMarkdown(self, title, text):
        data = {"msgtype": "markdown", "markdown": {"title": title, "text": text}}
        return self.post(data)

    # link类型
    def sendLink(self, title, text, messageUrl, picUrl=""):
        data = {"msgtype": "link", "link": {"text": text, "title": title, "picUrl": picUrl, "messageUrl": messageUrl}}
        return self.post(data)

    # ActionCard类型
    def sendActionCard(self, actionCard):
        data = actionCard.getData();
        return self.post(data)

    # FeedCard类型
    def sendFeedCard(self, links):
        data = {"feedCard": {"links": links}, "msgtype": "feedCard"}
        return self.post(data)

    def post(self, data):
        self.reset()
        self.sendCount += 1
        self.lastSendTime = datetime.now()
        post_data = json.JSONEncoder().encode(data)
        timestamp = str(round(time.time() * 1000))
        secret = self.secret
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        content = requests.post(f"{self.webhook}?access_token={self.token}&timestamp={timestamp}&sign={sign}", post_data,
                                headers={'Content-Type': 'application/json'})
        return content

    def reset(self):
        if not self.lastSendTime:
            self.sendCount = 0
        diff = DateUtils.diff(rrule.SECONDLY, self.lastSendTime, datetime.now())
        if diff > self.INTERVAL:
            self.sendCount = 0

    def isAvailable(self):
        if not self.lastSendTime:
            return True
        diff = DateUtils.diff(rrule.SECONDLY, self.lastSendTime, datetime.now())
        # 70秒内不允许发送超过18次，防止钉钉频率限制
        #每个机器人每分钟最多发送20条。如果超过20条，会限流10分钟。
        if self.sendCount < self.MAX or diff > self.INTERVAL:
            return True
        else:
            return False

# ActionCard类型消息结构
class ActionCard(object):
    """docstring for ActionCard"""
    title = ""
    text = ""
    singleTitle = ""
    singleURL = ""
    btnOrientation = 0
    hideAvatar = 0
    btns = []

    def __init__(self, arg=""):
        super(ActionCard, self).__init__()
        self.arg = arg

    def putBtn(self, title, actionURL):
        self.btns.append({"title": title, "actionURL": actionURL})

    def getData(self):
        data = {"actionCard": {"title": self.title, "text": self.text, "hideAvatar": self.hideAvatar,
                               "btnOrientation": self.btnOrientation, "singleTitle": self.singleTitle,
                               "singleURL": self.singleURL, "btns": self.btns}, "msgtype": "actionCard"}
        return data


# FeedCard类型消息格式
class FeedLink(object):
    """docstring for FeedLink"""
    title = ""
    picUrl = ""
    messageUrl = ""

    def __init__(self, arg=""):
        super(FeedLink, self).__init__()
        self.arg = arg

    def getData(self):
        data = {"title": self.title, "picURL": self.picUrl, "messageURL": self.messageUrl}
        return data


class RobotFactory:
    robots = []

    @staticmethod
    def init():
        tokens = settings.DINGTALK_ROBOTS.replace(',\\', '').strip().split(',')
        for i in range(int(len(tokens)/2)):
            token = tokens[i * 2]
            secret = tokens[i*2 + 1]
            RobotFactory.robots.append(DingtalkRobot(token, secret))

    @staticmethod
    def getAvailable():
        for robot in RobotFactory.robots:
            if robot.isAvailable():
                return robot
            else:
                continue
        return None

RobotFactory.init()

# 测试
# if __name__ == "__main__":
#     for i in range(5):
#         robot = RobotFactory.getAvailable()
#         if robot:
#             robot.sendText("现在时间：[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "]", False,
#                    ["13912345678 "])
#     robot.sendLink("link类型", "link类型内容link类型内容link类型内容link类型内容link类型内容link类型内容link类型内容", "http://www.baidu.com",
#                    "http://scimg.jb51.net/allimg/160716/103-160G61012361X.jpg")
#     robot.sendMarkdown("markdown类型", "## 标题2 \n##### 标题3 \n* 第一 \n* 第二 \n\n[链接](http://www.baidu.com/) \n")
#
#     ########
#     link1 = FeedLink()
#     link1.title = "我的github"
#     link1.picUrl = "https://avatars0.githubusercontent.com/u/3347358?v=3&u=318d72d3ec999cfe4c7f37765c9c1f92df79ab1c&s=400"
#     link1.messageUrl = "https://github.com/magician000"
#     link2 = FeedLink()
#     link2.title = "github官网"
#     link2.picUrl = "https://avatars0.githubusercontent.com/u/18586086?v=3&u=e6187b04ba02e3861ad4acccc5a1f1f5d46d40a0&s=400"
#     link2.messageUrl = "https://www.github.com/"
#     feeds = [link1.getData(), link2.getData()]
#
#     robot.sendFeedCard(feeds)
#
#     # ActionCard类型，两种跳转规则的设置见官方文档
#     # 整体跳转ActionCard类型
#     ac = ActionCard();
#     ac.title = "整体跳转ActionCard类型"
#     ac.text = "#### 整体跳转ActionCard类型 \n\n![TTTT](https://avatars0.githubusercontent.com/u/3347358?v=3&u=318d72d3ec999cfe4c7f37765c9c1f92df79ab1c&s=400) \n>整体\n跳转\nActionCard类型\n"
#     ac.singleTitle = "查看全文"
#     ac.singleURL = "https://github.com/magician000"
#     robot.sendActionCard(ac)
#     ########
#     # 独立跳转ActionCard类型
#     ac = ActionCard();
#     ac.title = "独立跳转ActionCard类型"
#     ac.text = "#### 独立跳转ActionCard类型 \n\n![TTTT](https://avatars0.githubusercontent.com/u/18586086?v=3&u=e6187b04ba02e3861ad4acccc5a1f1f5d46d40a0&s=400) \n>独立\n跳转\nActionCard类型\n"
#     ac.btnOrientation = 1
#     ac.putBtn("github", "https://github.com/magician000")
#     ac.putBtn("脑洞空间", "https://github.com/mind-boggling")
#     ac.singleTitle = ""
#     ac.singleURL = ""
#     robot.sendActionCard(ac)
